package cn.wolfcode.luowowo.search.service.impl;

import cn.wolfcode.luowowo.search.domain.HotelTemplate;
import cn.wolfcode.luowowo.search.query.HotelSearchQuery;
import cn.wolfcode.luowowo.search.service.IHotelEsService;
import cn.wolfcode.luowowo.search.service.repository.HotelTemplateEsRepository;
import com.alibaba.dubbo.config.annotation.Service;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.search.MultiMatchQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import java.util.List;

@Service
public class HotelEsServiceImpl implements IHotelEsService {

    @Autowired
    private HotelTemplateEsRepository hotelTemplateEsRepository;

    @Override
    public void save(HotelTemplate hotelTemplate) {
        hotelTemplateEsRepository.save(hotelTemplate);
    }

    @Override
    public List<HotelTemplate> findByDestName(String destName) {
        return hotelTemplateEsRepository.findByDestName(destName);
    }

    @Override
    public Page<HotelTemplate> query(HotelSearchQuery qo) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        if(qo.getRegionId() != -1){
            builder.withQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("regionId",qo.getRegionId()))
                                                        .must(QueryBuilders.termQuery("destId",qo.getDestId())));
        }else {
            builder.withQuery(QueryBuilders.termQuery("destId",qo.getDestId()));
        }

        builder.withPageable(PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize()));
        return hotelTemplateEsRepository.search(builder.build());
    }
}
